<?php

namespace app\common\model;

use app\common\Base;
use app\home\validate\LoginValidate;
use app\home\validate\RegValidate;
use app\home\validate\UserEditValidate;
use think\Model;

class User extends Model
{
    //验证错误抛出异常
    protected $failException = true;
    //引入trait
    use Base;
    //处理登录验证问题
    public function getLogin($arr)
    {
        //验证器验证数据
        $vali = new LoginValidate();
        $re = $vali->check($arr);
        if($re !== true){
            return $vali->getError();
        }
        $userinfo = self::getByEmail($arr['email']);
        return $userinfo['pwd'] == $arr['pwd'] ? ['id'=>$userinfo['id']] : [];
    }

    //处理注册
    public function createUser($arr)
    {
        //验证器验证数据
        $vali = new RegValidate();
        $re = $vali->check($arr);
        if($re !== true){
            return $vali->getError();
        }
        //验证验证码
        $re = self::create($arr);
        return $re->hidden(['pwd']) ?? [];
    }

    //处理修改个人数据
    public function editUser($arr,$id)
    {
        //验证器验证数据
        $vali = new UserEditValidate();
        $re = $vali->check($arr);
        if($re !== true){
            return $vali->getError();
        }
        return $this->editOne($arr,$id);
    }

    //处理头像路径的获取器
    public function getPicAttr($v)
    {
        return str_replace('\\','/',$v);
    }

    //处理微信登录的傻逼
    public function openid($arr)
    {
        //查询当前id是否存在
        $ishas = $this->where('openid',$arr['openid'])->find();
        if(!$ishas){
            //写入相关信息
            $re =  $this->saveOne($arr);
            return $re['id'];
        }else{
            $ishas->where('openid',$arr['openid'])->update($arr);
            return $ishas['id'];
        }
    }
}
